#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-11 下午3:15
import hashlib
from flask import Flask, request


class ChecksumCalcStream(object):
    def __init__(self, stream):
        self._stream = stream
        self._hash = hashlib.sha1()

    # noinspection PyShadowingBuiltins
    def read(self, bytes):
        rv = self._stream.read(bytes)
        self._hash.update(rv)
        return rv

    def readline(self, size_hint):
        rv = self._stream.readline(size_hint)
        self._hash.update(rv)
        return rv


# noinspection PyProtectedMember
def generate_checksum(request):
    env = request.environ
    stream = ChecksumCalcStream(env['wsgi.input'])
    env['wsgi.input'] = stream
    return stream._hash


app = Flask(__name__)

# 这样就可以返回请求的哈希值了
@app.route('/', methods=['GET'])
def special_api():
    hash = generate_checksum(request)
    files = request.files
    checksum = hash.hexdigest()
    return 'Hash was: %s' % checksum

if __name__ == '__main__':
    app.run(debug=True)